#include "RegisterWidget.h"
#include "ui_RegisterWidget.h"
#include"Global.h"
#include"HttpManage.h"
#include<QFile>
#include<QString>
RegisterWidget::RegisterWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RegisterWidget)
{
    ui->setupUi(this);
    //设置初始头像
    ui->LogoLabel->setPixmap(QPixmap(":/assets/cloud_gold.png").scaled((ui->LogoLabel->size()),Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
    //设置qss样式
    QFile file(":/assets/RegisterWidget.qss");
    if(file.open(QFile::OpenModeFlag::ReadOnly))
    {
        this->setStyleSheet(file.readAll());
        file.close();
    }
    else
    {
        qDebug("read qss failed\n");
    }
    //设置窗口图标
    QIcon icon(":/assets/cloud_red.png");
    this->setWindowIcon(icon);
    ui->HintLabel->setProperty("state","normal");
    repolish(ui->HintLabel);
    connect(HttpManage::GetInstance().get(),&HttpManage::sig_reg_mod_finish,this,&RegisterWidget::slot_reg_mod_finish);

    InitHttpHandlers();
}

RegisterWidget::~RegisterWidget()
{
    delete ui;
}

void RegisterWidget::on_GetVerifyPushButton_clicked()
{
    QString email = ui->EmailLineEdit->text();
    QRegularExpression regex(R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)");
    bool is_match = regex.match(email).hasMatch();
    if(is_match)
    {
        ShowTip(tr("验证码发送成功"),true);
        //发送验证码
        QJsonObject json_obj;
        json_obj["email"] = email;
        HttpManage::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_verifycode"),json_obj,ReqId::ID_GET_VERIFY_CODE,Modules::REGISTERMOD);
    }
    else
    {
        ShowTip(tr("邮箱地址不正确"),false);
    }
}

void RegisterWidget::slot_reg_mod_finish(ReqId id, QString res , ErrorCode err)
{
    if(err != ErrorCode::SUCCESS)
    {
        ShowTip(tr("网络请求错误"),false);
        return ;
    }
    //解析json字符串res转换为QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    if(jsonDoc.isNull())
    {
        ShowTip(tr("json解析失败"),false);
        return;
    }
    //json 解析错误
    if(!jsonDoc.isObject())
    {
        ShowTip(tr("json 解析失败"),false);
        return;
    }
    _handlers[id](jsonDoc.object());
    return ;
}

void RegisterWidget::ShowTip(QString str,bool is_ok)
{
    if(is_ok)
    {
        ui->HintLabel->setProperty("state","normal");
    }
    else
    {
        ui->HintLabel->setProperty("state","err");
    }
    ui->HintLabel->setText(str);
    repolish(ui->HintLabel);
}

void RegisterWidget::InitHttpHandlers()
{
    //注册获取验证码回包逻辑
    _handlers.insert(ReqId::ID_GET_VERIFY_CODE,[this](const QJsonObject& jsonObj)
    {
        int error = jsonObj["error"].toInt();
        if(error != ErrorCode::SUCCESS)
        {
            ShowTip(tr("参数错误"),false);
            return ;
        }
        auto email = jsonObj["email"].toString();
        ShowTip(tr("验证码发送成功，请注意查收"),true);
        qDebug()<<"email is"<<email;
    });
    //注册注册用户回包逻辑
       _handlers.insert(ReqId::ID_REG_USER, [this](QJsonObject jsonObj)
       {
           int error = jsonObj["error"].toInt();
           if(error != ErrorCode::SUCCESS)
           {
               ShowTip(tr("参数错误"),false);
               return;
           }
           auto email = jsonObj["email"].toString();
           ShowTip(tr("用户注册成功"), true);
           qDebug()<< "email is " << email ;
       });
}

void RegisterWidget::on_RegisterPushButton_clicked()
{
    if(ui->UserLineEdit->text() == "")
    {
        ShowTip(tr("用户名不能为空"),false);
        return;
    }
    if(ui->EmailLineEdit->text() == "")
    {
        ShowTip(tr("邮箱不能为空"),false);
        return;
    }
    if(ui->PwdLineEdit->text() == "")
    {
        ShowTip(tr("密码不能为空"),false);
        return;
    }
    if(ui->ConfirmPwdLineEdit->text() == "")
    {
        ShowTip(tr("确认密码不能为空"),false);
        return;
    }
    if(ui->PwdLineEdit->text() != ui->ConfirmPwdLineEdit->text())
    {
        ShowTip(tr("密码和确认密码不匹配"),false);
        return;
    }
    if(ui->VerifyKeyLineEdit->text() == "")
    {
        ShowTip(tr("验证码不能为空"),false);
        return;
    }
    QJsonObject json_obj;
    json_obj["user"] = ui->UserLineEdit->text();
    json_obj["email"] = ui->EmailLineEdit->text();
    json_obj["passwd"] = md5Encrypt(ui->PwdLineEdit->text());
    json_obj["confirm"] = md5Encrypt(ui->ConfirmPwdLineEdit->text());
    json_obj["verifycode"] = ui->VerifyKeyLineEdit->text();
    HttpManage::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/user_register"),json_obj, ReqId::ID_REG_USER,Modules::REGISTERMOD);
}

void RegisterWidget::on_CancelPushButton_clicked()
{
    this->hide();
}
